package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.UserAndRoleMapper;
import com.ushine.web.base.model.relation.UserAndRoleDO;
import com.ushine.web.base.service.IUserAndRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * @Author: yls
 * @Date: 2021/4/22 9:38
 * @Description: 用户角色关联 -- ServiceImpl
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class UserAndRoleServiceImpl extends ServiceImpl<UserAndRoleMapper, UserAndRoleDO> implements IUserAndRoleService {

    @Override
    public Boolean insertUserRole(UserAndRoleDO userAndRoleDO) {
        LambdaQueryWrapper<UserAndRoleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAndRoleDO::getUserId, userAndRoleDO.getUserId());
        remove(queryWrapper);
        return save(userAndRoleDO);
    }

    @Override
    public Boolean insertUserRoles(List<UserAndRoleDO> userAndRoles) {
        userAndRoles = Optional.ofNullable(userAndRoles).orElse(new ArrayList<>(0));
        Set<Long> userIds = userAndRoles.stream().map(UserAndRoleDO::getUserId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserAndRoleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserAndRoleDO::getUserId, userIds);
        remove(queryWrapper);
        saveBatch(userAndRoles);
        return true;
    }
}
